import { createContext, ReactNode, useContext, useEffect, useMemo, useState } from "react";
import { useIdentityProvider } from "./useSIWPIdentity";
import { UserModel, User } from "../db/models/userModel";

type AccountContextType = {
    userInfo?: User;
}

export const AccountContext = createContext<AccountContextType | undefined>(undefined);
export const useAccountProvider = () => {

    const context = useContext(AccountContext);
    if (!context) {
        throw new Error('useAccounttProvider must be used within an AccountProvider');
    }
    return context;
}

export function AccountProvider({ children }: Readonly<{
    children: ReactNode
}>) {
    const [userInfo, setUserInfo] = useState<User | undefined>(undefined);
    const { identityId } = useIdentityProvider();

    const getUserInfo = async (userName: string) => {
        const userModel = new UserModel();
        const _userInfo = await userModel.getByUserName(userName);
        setUserInfo(_userInfo == null ? undefined : _userInfo);
    }

    useEffect(() => {
        if (typeof identityId !== "undefined") {
            getUserInfo(identityId);
        }
    }, [identityId]);


    const contextValue = useMemo(() => ({
        userInfo
    }), [userInfo]);

    return (
        <AccountContext.Provider value={contextValue}>
            {children}
        </AccountContext.Provider>
    );

}